/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.andersen.web.controller;

import com.andersen.database.entity.UserEntity;
import com.andersen.web.beans.UserCommandForm;
import com.andersen.web.validating.EditUserValidator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author Corvus 11
 */
@Controller
public class EditUserController extends AbstractController{
    
    @Autowired
    EditUserValidator validator;
    
    /**
     * Заполнить аттрибут с содержимым формы
     * @param user объект пользователя
     * @param account
     * @return 
     */
    private UserCommandForm fillForm(UserEntity user) {
        UserCommandForm fmt = new UserCommandForm();
        
        fmt.setLogin(user.getLogin());
        fmt.setPrevLogin(user.getLogin());
        fmt.setId(user.getId());
        
        return fmt;
    }
    
    @RequestMapping(value = "/account", method = RequestMethod.GET)
    public String openEditAccountPage(ModelMap map, HttpServletRequest request) {
        
        String login = SecurityContextHolder.getContext().getAuthentication().getName();
        
        UserEntity user = userService.getUser(login);
        
        UserCommandForm form = fillForm(user);
        
        map.addAttribute("userCommandFormat",form);
        
        LOG.info(form);
        
        return "edit_user";
    }
    
    /*@RequestMapping(value = "/user", method = RequestMethod.GET)
    public String openEditUserPage(ModelMap map,
                                   @RequestParam(required = true, value = "id") String userId,
                                   HttpServletResponse response) {

        if (!hasGrantedAuthority(Roles.ADMIN)) {
            response.setStatus(403);
            return "index";
        }
        
        long id = Long.valueOf(userId);
        UserEntity user = userService.getUser(id);
        UserCommandForm form = fillForm(user, false);
        map.addAttribute("userCommandFormat",form);
        
        LOG.info(form);
        
        return "edit_user";
    }*/
    
    private boolean processSaving(UserCommandForm form) {
        UserEntity ent = new UserEntity();
            ent.setId(form.getId());
            ent.setLogin(form.getLogin());
            if (!form.getPassword().isEmpty()) {
                Md5PasswordEncoder enc = new Md5PasswordEncoder();
                ent.setPassword(enc.encodePassword(form.getPassword(),null));
            }
            boolean resultError = !userService.updateUser(ent);
            if (!resultError) {
                form.setPrevLogin(form.getLogin());
            }
            return resultError;
    }
    
    @RequestMapping(value = "/account", method = RequestMethod.POST)
    public String applyChanges(@ModelAttribute("userCommandFormat") UserCommandForm command,
        BindingResult result, ModelMap map, HttpServletResponse response) {
        
        LOG.info(command);
        
        validator.validate(command, result);
        
        if (result.hasErrors()) {
            return "edit_user";
        } else {
            boolean err = processSaving(command);
            map.put("resultError", err);
        }
        return "edit_user";
    }  
    
}
